
/**
	Test mockup of transfer pop functions for
	Pusher integration

	tlpop_shortlist_player
	tlpop_pop_transfer_bid
	tlpop_pop_transfer_ajax
	tlpop_buttons
	tlpop_post_transfer_bid
	tlpop_show_msg
	transfer_pop_up_countdown
*/

var tlpop_timer = false;

function transfer_pop_up_countdown(deadline) {
	deadline = deadline - 10;
	// set the date we're counting down to
	//var target_date = new Date("February 18, 2014 15:33:00").getTime();

	if (deadline == "") alert("Deadline: " + deadline);
	//console.log("SRVTM: "+server_time);

	var target_date = deadline*1000;
	
	var client_date = new Date().getTime();
	var target_time = client_date + target_date;
	
	// variables for time units
	var days, hours, minutes, seconds;

	// Reset JS countdown
	if (tlpop_timer)
		clearInterval(tlpop_timer);

		var countdown = $("#tl_pop_countdown");
	// update the tag with id "countdown" every 1 second
	tlpop_timer =  setInterval(function () {
	
		var seconds_left = (target_time - new Date().getTime())/1000;

		// do some time calculations
		days = parseInt(seconds_left / 86400);
		seconds_left = seconds_left % 86400;

		hours = parseInt(seconds_left / 3600);
		seconds_left = seconds_left % 3600;

		minutes = parseInt(seconds_left / 60);
		seconds = parseInt(seconds_left % 60);

		if (hours < 10 && days < 1)
			hours = "0" + hours;
		if (minutes < 10)
			minutes = "0" + minutes;
		if (seconds < 10)
			seconds = "0" + seconds;

		// format countdown string + set tag value
		if (days > 0)
			countdown.html(days + "d " + hours + "h");
		else if (hours > 0)
			countdown.html(hours + ":" + minutes + ":" + seconds);
		else if (seconds > 0 || minutes > 0) {
			countdown.html(minutes + ":" + seconds);
			if (minutes < 1 && seconds < 11)
				countdown.addClass("blink");
		}
		else {
			clearInterval(tlpop_timer);
			var player_id = $("#tlpop_hischat").find("#this_player_id").text();
			$.post("/ajax/transfer_bids.ajax.php",{"type":"get_transfer_final_bid","player_id":player_id,"session_id":SESSION["id"]},function(data) {
				// Transfer has expired
				var array = $.parseJSON(data);
				if (array != undefined) {
					var club_name = (array["club_name"]) ? array["club_name"] : "";
					var player_name = (array["player_name"]) ? array["player_name"] : "";
					var club_id = (array["club_id"]) ? array["club_id"] : "";
					var player_id = (array["player_id"]) ? array["player_id"] : "";
					var bid = (array["bid"]) ? array["bid"] : "";
					if (club_id>0) {
						$("#tlpop_form").html("<p style='padding-top: 50px; font-size: 110%; line-height: 1.4em;'><a href='/club/"+club_id+"/'>"+club_name+"</a><br />"+pagecontent["t69"]+"<br /><a href='"+get_player_link({"player":{"id":player_id, "name":player_name}, "only_url":true})+"'>"+player_name+"</a><br />"+pagecontent["t70"]+"<br /><strong>"+money(bid)+"</strong></p>");
						$("#tlpop_time").html("<p style='text-align: center; padding-right: 20px;'>"+pagecontent["t71"]+"</p>");
					}
					// TODO Check for no bid!
					else {
						$("#tlpop_form").html("<p style='padding-top: 50px; font-size: 110%; line-height: 1.4em;'>There were<br /><strong>no bids</strong><br />for<br /><strong>" + player_name + "</strong></p>");
						$("#tlpop_time").html("<p style='text-align: center; padding-right: 20px;'>"+pagecontent["t71"]+"</p>");
					}
				} else {
					// TODO AJAX no response.
					$("#tlpop_form").html("<p style='padding-top: 50px; font-size: 110%; line-height: 1.4em;'>An error occurred<br />please reload<br />the transfer list</p>");
					$("#tlpop_time").html("<p style='text-align: center; padding-right: 20px;'>"+pagecontent["t71"]+"</p>");

				}
			});
		}

		// Function for blinking text.
		$(".blink").animate({opacity:0}, 500, "linear", function(){
			$(this).animate({opacity:1}, 500);
		});

	}, 1000);


	/*
	$.ajax({
            url: "/ajax/transfer_time.ajax.php",
            type: "POST",
            dataType: 'json',
            cache: false,
            success: function (data) {
                server_time = data["time"];
            }
	})
	.then(function(){
		//
		//ALL OF THE ABOVE
		//
	});
	*/
}

/* More gentle version of shortlist player for the transfer popup */
function tlpop_shortlist_player(player_id)
{
	$.post("/ajax/players_shortlist.ajax.php",{"player_id":player_id},function(data){
		if(data != null)
		{
			$("#tlpop_shortlist_button").hide();
			$("#tlpop_shortlist_response").append(global_content[475]).css("line-height", "40px").show();
		}
	},"json");
}

function tlpop_pop_transfer_bid(bid_old,pro_old,player_id,name_old)
{
	//modal.html(get_loading_img()).show();

	tlpop_pop_transfer_ajax(player_id,"",true);

	//DEBUG


	Pusher.log = function(message) {
	  if (window.console && window.console.log) {
	      window.console.log(message);
	  }
	};


	// Activate Pusher and subscribe to channel as well as listen for events.
	//var pusher = new Pusher(PUSHER_APP_KEY);
	var channel = pusher.subscribe('transfer_player_' + player_id);
	channel.bind('new_bid', function(data) {
		// Trigger re-get transfer data
		if (data["response"]["id"]>0 && SESSION["id"]==data["response"]["id"]) {
			var message = (data["response"]["message"]) ? data["response"]["message"] : "";
			tlpop_show_msg(message);
		}
		console.log("new bid occured");
		console.log(data);
		tlpop_pop_transfer_ajax(player_id, message, false, data);

		//alert('An event.new_bid was triggered with message: ' + data.message);
	});

}

function tlpop_pop_transfer_ajax(player_id, message, initial, data)
{
	if (!initial) {
		console.log("push update");
		transfer_pop_up_countdown(data['time_left']);
		
		if (data['first_mover']!=SESSION['id'] && data['first_mover']>0) var min_bid = number_format(Math.floor(data['bid']*1.1+1));
		else var min_bid = number_format(Math.floor(data['bid']*1.025+1));
				
		$("#minbid").text(min_bid);
		$("#transfer_bid").val(min_bid);
		
		var bid_history = data['bid_history'];
		$("#tlpop_history").html("");
		for ($i=0; $i<3; $i++)
			{
				if (!bid_history[$i])
					break;
				var bh_club_link = (bid_history[$i]["club_id"]<1) ? bid_history[$i]["club_name"] : '<form id="clubform_'+$i+'" method="post" style="display:inline; cursor:pointer;" action="/club/'+bid_history[$i]["club_id"]+'"><span onclick="clubform_'+$i+'.submit();">'+bid_history[$i]["club_name"]+'</span></form>'
				$("#tlpop_history").append($("<li />").append(
					$("<span />").addClass("logo").append(((bid_history[$i]["club_id"]>0) ? "<img src='/pics/club_logos/" + bid_history[$i]["club_id"] + "_25.png' />" : "")),
					$("<span />").addClass("name").html(bh_club_link),
					$("<span />").addClass("bid").text(bid_history[$i]["bid"])
				))
			}
			
			var color, text;
			if (data['club_id']==SESSION['id']) {
				color = "#3b0";
				text = pagecontent['t67'];
			} else {
				color = "#700";
				text = pagecontent['t66'];
			}
			
		$("#tlpop_status").html($("<div>").append($("<p />").addClass("bold text_center").text(pagecontent["t63"])).append($("<h2 />").addClass("text_center text_white").css({"color":"white", "letter-spacing":"0.03em"}).text(text))
		).css({"background-color":color});
		/*
			update the 'bidding status'
		*/
	
	
	
	} else {
		$.post("/ajax/transfer_bids.ajax.php",{"type":"get_transfer_bid","player_id":player_id,"session_id":SESSION["id"]},function(data){

			if(data["wrong_session"])
			{
				modal.html($("<div />").append(
					$("<p />").addClass("error").html(data["error"]+"<br />"+data["error1"]),
					$("<div />").addClass("msgbuttons").append(make_button(global_content["ok"],"page_refresh()"))
					)).header(global_content["make_bid"]);
					body_refresh();
				return;
			}

			if(data["transfer"]["expired"])
			{ // Transfer expired
				modal.html($("<div />").append(
					$("<h2 />").html(''),
					$("<p />").text(data["expired_text"]),
					$("<div />").addClass("msgbuttons").append(make_button(global_content["ok"],"modal.hide()"))
				)).header(global_content["make_bid"]);
				return;
			}

			var bid = data["transfer"]["next_bid"];
			var next_bid = (initial) ? bid : "0";
			var player_name = data["transfer"]["player_name"];
			var player_wage = data["p"]["wage"];
			var player_position = data["p"]["favposition_long"];
			var player_routine = data["p"]["rutine"];
			var player_country = data["p"]["player_country"];
			var player_age = data["p"]["age"];
			var player_rec = data["p"]["rec"];
			var pro = data["is_pro"];
			var deadline = data["deadline"];
			var current_status = data["current_status"];
			var my_last_bid = data["my_last_bid"];
			var bid_history = data["bid_history"];
			var bid_history_html = "";
			var agent = "";
			if(data.agent && data.agent.id && SESSION.id == data.agent.clubid) {
				agent = $tpl('div', [
					$tpl('div', [(global_content[650] || 'Agent') + ': ' + data.agent.max_bid]),
					$tpl('span', '', 'button', [global_content.delete]).click(function(){$('#modal, #modal .inner').css({background:'', padding: ''}); pop_delete_agent(data.agent.id, player_name)}).css({padding: '0 15px'}).tooltip("Max " + data.agent.max_bid)
					]);
			}

			var $html = $("<div />").addClass("std");
			//console.log(pagecontent);
			//console.log(global_content);
			$html.append(
				// Player info table
				$("<div />").addClass("tlpop_white").css({"border-bottom-right-radius":"2px 4px", "border-bottom-left-radius":"2px 4px"}).append(
					$("<table />").append(
						$("<tr />").html(
							'<td class="player_image" rowspan="5" class="text_center" style="width:150px">' + data["player_image"] + '<br />' + player_rec + '</td>' +
							'<td class="very_large" colspan="2"><form style="display:inline;" id="namelink_form" method="post" action="'+get_player_link({"player":{"id":player_id, "name":player_name}, "only_url":true})+'"><span onclick="namelink_form.submit()" style="cursor:pointer;">' + player_name + '</span></form> ' + get_flag(player_country) + '</td>' +
							// Countdown timer #tlpop_time
							'<td rowspan="6" id="tlpop_time">' +
								'<img src="/pics/ultra2/clock2.png" alt="Clock" />' +
								global_content["time_left"].toUpperCase() +
								'<div id="tl_pop_countdown"><div></div></div>' +
							'</td>'
						),
						$("<tr />").html('<td style="width: 12%;">'+global_content['position']+':</td><td>'+player_position+'</td>'),
						$("<tr />").html('<td>'+global_content['age']+'</td><td>'+player_age+'</td>'),
						/* $("<tr />").html('<td>'+global_content['wage']+'</td><td>'+money(player_wage)+'</td>'), */
						$("<tr />").html('<td>'+global_content['routine']+'</td><td>'+player_routine+'</td>'),
						$("<tr />").html('<td colspan="2" id="tlpop_shortlist"><span id="tlpop_shortlist_button" class="button" style="padding: 0; min-width: 180px" onclick="javascript:tlpop_shortlist_player(' + player_id + ');"><span class="button_border" style="padding: 0 20px; min-width: 150px">' + global_content[474] + '</span> <span class="sprite_big icon_shortlistbutton" style="margin: 5px 0 0 -10px; float: right; position: absolute;"></span></span><span id="tlpop_shortlist_response" style="display:none;"></span></td>')
					)
				),
				// Bid divs
				$("<div />").addClass("tlpop_white").css({"min-height":"230px", "border-radius":"2px 4px"}).append(
					// Bid form div #tlpop_form
					$("<div />")
					.attr("id", "tlpop_form")
					.addClass("text_center")
					.css({"position":"relative", "float":"left", "margin":"0", "width":"467px", "background-color":"transparent", "min-height":"210px", "padding":"12px 10px 0 10px", "border-top-left-radius":"2px 4px", "border-bottom-left-radius":"5px"})
					.append(
						// Bid form
						$("<form />").attr("id","transfer_bid_form").append(
							"<input type='hidden' value='"+bid+"' name='min_bid' id='min_bid' />",
							"<input type='hidden' value='"+player_name+"' id='bid_player_name' />",
							"<div>"
							+"<p style='font-size: 110%;'>"
							+pc_replace(global_content["bid_on_player"],{"[span]":"<strong class='large'>","[/span]":"</strong>","[player]":player_name})
							+"</p>"
							+"<input type='text' name='transfer_bid' id='transfer_bid' value='"+next_bid+"' class='emboss' style='padding: 12px; width:280px; font-size: 100%;' onkeyup='update_transfer_radio(this)' tabindex='"+(tabindex++)+"' focus/>"
							+'<span style="margin-left: -30px;">' + money_big() + '</span>'
							+"<p class=\"new_subtle\" style='padding: 0; margin: 5px 0 3px 0;'>"+pc_replace(global_content["min_bid_is"],{"[bid]":"<strong id='minbid'>"+bid+"</strong>"})+"</p>"
							+"</div>"
						)
					),
					// Bid status div (dyn. coloured) #tlpop_status
					$("<div />")
					.attr("id", "tlpop_status")
					.css({"background-color":current_status["color"], "float":"right", "margin":"0", "width":"182px", "padding":"20px 25px", "min-height":"190px", "border-top-right-radius":"2px 4px", "border-bottom-right-radius":"2px 4px"})
					.append(
						$("<p />").addClass("bold text_center").text(pagecontent["t63"]),
						$("<h2 />").addClass("text_center text_white").css({"color":"white", "letter-spacing":"0.03em"}).text(current_status["text"]),
						$("<p />").addClass("text_white text_center").css({"color":"white", "margin-top":"35px"}).text(my_last_bid),
						$("<p />").addClass("text_white text_center").css({"color":"white", "margin-bottom":"0", "padding-bottom":"0"}).html(agent)
					)
				),
				// Bid history and chat
				$("<div />").attr("id", "tlpop_hischat").append(
					$("<div />").css({"width":"100%", "margin":"0", "margin-right":"10px", "background-color":"#333333", "min-height":"210px", "border-radius":"2px 4px"}).append(
						$("<h3 />").css({"color":"#FFF", "margin":"0", "padding":"10px", "font-weight":"normal", "border-radius":"2px 4px", "letter-spacing":"0.03em"}).text(pagecontent["t64"]),
						$("<ul />").addClass("black").attr("id", "tlpop_history").css({"border-radius":"2px 4px"})
					),
					$("<div />").attr("id", "transfer_channel").html('transfer_player_' + player_id).hide(),
					$("<div />").attr("id", "this_player_id").html(player_id).hide()
	/*
					$("<div />").css({"float":"right", "width":"355px", "background-color":"white"}).attr("id", "tlpop_chat").append(
						// ADD CHAT HERE!
						$("<textarea />").attr("rows", "5").attr("cols", "10")
					)
	*/
				)
			);
			// Foreach historic bid, add li
			for ($i=0; $i<3; $i++)
			{
				if (!bid_history[$i])
					break;
				var bh_club_link = (bid_history[$i]["club_id"]<1) ? bid_history[$i]["club_name"] : '<form id="clubform_'+$i+'" method="post" style="display:inline; cursor:pointer;" action="/club/'+bid_history[$i]["club_id"]+'"><span onclick="clubform_'+$i+'.submit();">'+bid_history[$i]["club_name"]+'</span></form>'
				$html.find("#tlpop_history").append($("<li />").append(
					$("<span />").addClass("logo").append(((bid_history[$i]["club_id"]>0) ? "<img src='/pics/club_logos/" + bid_history[$i]["club_id"] + "_25.png' />" : "")),
					$("<span />").addClass("name").html(bh_club_link),
					$("<span />").addClass("bid").text(bid_history[$i]["bid"])
				))
			}
			if(!this_is_tutorial)
			{
				var pc1 = pc_replace(global_content["agent_on_player"], {"[span]":"<strong>", "[/span]":"</strong>", "[player]":player_name});
				var pc2 = global_content["cost"]+":";
				$html.find("#transfer_bid_form").append(
						$("<input />").attr("type","checkbox").attr("id","transfer_agent").val(1).attr("tabindex",tabindex++),
						$("<label />").attr("for","transfer_agent").append(
							"<span class='new_subtle'>"+pc1+"</span>",
							" <span class='new_subtle'><img src='/pics/pro_icon.png?' style=\"margin-bottom: -3px\" /></span>"
						)
					);
			}
			$html.find("#transfer_bid_form").addClass("msgbuttons").css({"padding":"10px"}).append(
				$(make_button(" "+global_content["make_bid"]+" <ib class='auction_hammer_white sprite_big'></ib>","tlpop_post_transfer_bid("+player_id+");","button_large")).attr("tabindex",tabindex++).attr("id", "tlpop_bid_button"),
				data["pro_button"]
			);
			// Make #modal transparent
			$("#modal").css("background-color", "transparent");
			$("#modal").find("div.inner").css({"background-color":"transparent", "padding":"0"});
			// Make #modal wider and center it
			modal.html($html,global_content.make_bid).show().setWidth("720px").reposition("-360px");
			//modal.html($html,global_content.make_bid).show().reposition("-360px");
		//^^^^^^^^^^til nyt modal show
			// Hide Pro bid button & make TA checkbox
			$("#tlpop_bid_button_pro").hide();
			make_checkbox("transfer_agent");
			emboss();
			// Start (and end previous) countdown clock(s)
			transfer_pop_up_countdown(deadline);
			// Add message (bid response from ajax)  to HTML
			if (message) {
				tlpop_show_msg(message);
			}
		},"json");
	}
}

/* Button swapping function for transfer agent checkbox */
function tlpop_buttons() {
	if ($('#transfer_agent').is(':checked')) {
		$("#tlpop_bid_button").hide();
		$("#tlpop_bid_button_pro").show();
	}
	else {
		$("#tlpop_bid_button").show();
		$("#tlpop_bid_button_pro").hide();
	}
}


function tlpop_post_transfer_bid(player_id)
{
	var $transfer = $("#transfer_bid");
	var bid = $transfer.val().replace(/[^0-9]/g,"");
	var min_bid = $("#min_bid").val().replace(/[^0-9]/g,"");
	var player_name = $("#bid_player_name").val();
	var transfer_type = $("#transfer_agent").is(":checked") ? "agent" : "bid";
	if(parseInt(bid) < parseInt(min_bid))
	{
		//error
		tlpop_show_msg("Minimum bid not met", "990000");
		return false;
	}

	button_disable($("#bid_button"));
	$("#transfer_method").siblings(".error").remove();

	$.ajax({
            url: "/ajax/transfer_bids.ajax.php",
            type: "POST",
            dataType: 'json',
            data: {"type":"transfer_bid","player_id":player_id,"transfer_type":transfer_type,"bid":bid,"session_id":SESSION["id"]},
            cache: false,
            success: function (data) {
                bid_data = data;
				// Tutorial
				if(SESSION["tutorial"]==1 && bid_data!="" && bid_data!=null && typeof tutorial_transferbid_made == "function") {
					//call below don't work if no previous bid on player!!!???!!!???!!!???????!!!
					tutorial_transferbid_made();
					return;
				}
            }
        })
        .then(function(){
		// Messages
		var message_key = false;
		if (bid_data["error"]) message_key = "error";
		else if (bid_data["outbid"]) message_key = "error";

		var message = "";
		if (message_key) {
			message = bid_data[message_key];
			tlpop_show_msg(message, "990000");
		}

		if (bid_data!="" && bid_data!=null)
		{
			if(transfer_type == "agent") pro_update();
			// Tutorial
			//if(typeof tutorial_transferbid_made == "function") tutorial_transferbid_made();
			// ^^^^called above
		}
		return false;
	});
}

function tlpop_show_msg(message, color) {
	color = typeof color !== 'undefined' ? "#"+color : "darkgreen";
	if (message != "") {
		// Remove previous messages
		$(".msgbuttons").siblings(".error").remove();
		// Necessary for positioning of .error
		$(".msgbuttons").css("position","relative");
		// Insert div for error messages
		var $error = $("<p class='error' />").insertBefore(".msgbuttons");
		$error.css({"position":"absolute", "top":"0", "left":"0", "background-color":color, "width":"468px", "padding":"4px 10px", "border-radius":"0", "z-index":"105"}).append(message);
		//$error.css({"position":"absolute", "top":"0", "left":"0", "background-color":color, "width":"468px", "padding":"4px 10px", "border-radius":"0"}).append(message);
		//^^which ??
		// Fade out messages after 5s
		setTimeout(function(){
			$(".msgbuttons").siblings(".error").fadeOut("5000");
		}, 5000);
	}
}

function $tpl(elem, id, classes, html, attrs) {
	var $e = $('<' + elem + '/>');
	if ( Object.prototype.toString.call( id ) === '[object Array]' ) {
		html = id;
		id = '';
	}
	if ( id ) $e.attr('id', id);
	if ( classes ) $e.addClass(classes);
	if ( html ) {
		if ( Object.prototype.toString.call( html ) === '[object Array]' ) {
			for (var i = 0; i<html.length; i++) {
				$e.append(html[i]);
			}
		} else {
			$e.html(html);
		}
	}
	if ( typeof attrs  === 'object' ) {
		for(var i in attrs) {
			$e.attr(i, attrs[i]);
		}
	}
	return $e;
}
